/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.epcs.util;

import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 * 
 * @author Hà Hải Đăng
 * 
 *         Note: Hibernate uses one or two SessionFactory to connection one database If you create
 *         more than 2 SessionFactory, Hibernate may be crashed.
 * 
 *         And different from other Utility Class (such as DBUtil,...) Hibernate should not return
 *         Session from HibernateUtil. Why? Because Session is the representation of one action
 *         (that may cooperate with Transaction) So that, in a Transaction you my beed to use more
 *         than on Session
 * 
 */
public class DBUtil {

	private static SessionFactory sessionFactory = null;

	public DBUtil() {
		sessionFactory = null;
	}

	public static void initSessionFactory() {

		// Create the SessionFactory from standard (hibernate.cfg.xml)
		// config file.

		Configuration configuration = new Configuration().configure();
		Properties configure = configuration.getProperties();
		ServiceRegistryBuilder serviceBuilder = new ServiceRegistryBuilder().applySettings(configure);
		ServiceRegistry serviceRegistry = serviceBuilder.buildServiceRegistry();

		sessionFactory = new Configuration().configure().buildSessionFactory(serviceRegistry);
		
	}

	public static Session getSession() {
		Session session = null;
		try {
			if (sessionFactory == null) {
				initSessionFactory();
				System.out.println("init session factory");
			}

			session = sessionFactory.openSession();
		} catch (HibernateException ex) {
			System.out.println("Error: Cannot get Session");
			System.out.println(ex.getMessage());
		}
		return session;
	}
	
	public static Session getCurrentSession() {
		Session session = null;
		try {
			if (sessionFactory == null) {
				initSessionFactory();
				System.out.println("init session factory");
			}

			System.out.println("init session");
			session = sessionFactory.getCurrentSession();
		} catch (HibernateException ex) {
			System.out.println("Error: Cannot get current Session");
			System.out.println(ex.getMessage());
		}
		return session;
	}
	
	public static void closeSessionFactory(){
		if (sessionFactory != null){
			if (!sessionFactory.isClosed()){
				sessionFactory.close();
				
			}
		}		
	}
}
